//是否支持存储，这个是用来保存每一步的
function supportstorage() {
	return typeof window.localStorage == 'object';
}
//句柄保存布局
function handleSaveLayout() {
	//获取画布div
	const e = $(".drag-view").html();
	if (!stopsave && e !== window.dragViewHtml) {
		//e != window.drag-viewHtml：当前从.drag-view元素中获取的HTML内容（存储在e中）必须与存储在window.drag-viewHtml中的HTML内容不同。
		//更新状态和变量：
		stopsave++;
		window.dragViewHtml = e;
		//开始绘制div到drag-view这个div中
		saveLayout();
		stopsave--;
	}
}
//布局历史
var layouthistory;
//保存布局
function saveLayout(){
	//获取布局历史
	var data = layouthistory;
	//如果没有历史，则创建一个空的对象
	if (!data) {
		data={};
		data.count = 0;
		data.list = [];
	}
	//删除多余的历史
	if (data.list.length>data.count) {
		for (i=data.count;i<data.list.length;i++)
			data.list[i]=null;
	}
	//将当前布局添加到历史列表中
	data.list[data.count] = window.drag-viewHtml;
	//更新历史计数
	data.count++;
	//是否可以保存数据到本地，如果可以，则保存到本地
	//这里的data数据是整个drag-view这个div的数据
	if (supportstorage()) {
		//console.log("保存布局到本地-->"+JSON.stringify(data));
		localStorage.setItem("layoutdata",JSON.stringify(data));
	}
	//更新全局变量
	layouthistory = data;
	//console.log("当前保存的历史元素数据-->"+JSON.stringify(data));
	/*$.ajax({
		type: "POST",
		url: "/build/saveLayout",
		data: { layout: $('.drag-view').html() },
		success: function(data) {
			//updateButtonsVisibility();
		}
	});*/
}

//下载布局
function downloadLayout(){
	$.ajax({
		type: "POST",
		url: "/build/downloadLayout",
		data: { layout: $('#download-layout').html() },
		success: function(data) { window.location.href = '/build/download'; }
	});
}

function downloadHtmlLayout(){
	$.ajax({
		type: "POST",
		url: "/build/downloadLayout",
		data: { layout: $('#download-layout').html() },
		success: function(data) { window.location.href = '/build/downloadHtml'; }
	});
}

//撤销布局
function undoLayout() {
	var data = layouthistory;
	// console.log(data);
	if (data) {
		//如果当前历史计数小于2，则不能撤销
		if (data.count<2) return false;
		//更新当前历史计数
		window.dragViewHtml = data.list[data.count-2];
		data.count--;
		$('.drag-view').html(window.dragViewHtml);
		if (supportstorage()) {
			localStorage.setItem("layoutdata",JSON.stringify(data));
		}
		return true;
	}
	return false;
	/*$.ajax({
		type: "POST",
		url: "/build/getPreviousLayout",
		data: { },
		success: function(data) {
			undoOperation(data);
		}
	});*/
}

//恢复布局
function redoLayout() {
	var data = layouthistory;
	if (data) {
		if (data.list[data.count]) {
			window.dragViewHtml = data.list[data.count];
			data.count++;
			$('.drag-view').html(window.dragViewHtml);
			if (supportstorage()) {
				localStorage.setItem("layoutdata",JSON.stringify(data));
			}
			return true;
		}
	}
	return false;
	/*
	$.ajax({
		type: "POST",
		url: "/build/getPreviousLayout",
		data: { },
		success: function(data) {
			redoOperation(data);
		}
	});*/
}

//处理js id
function handleJsIds() {
	//处理模态框id
	handleModalIds();
	//处理折叠面板id
	handleAccordionIds();
	//处理轮播id
	handleCarouselIds();
	//处理tabs id
	handleTabsIds()
}
function handleAccordionIds() {
	var e = $(".drag-view #myAccordion");
	var t = randomNumber();
	var n = "accordion-" + t;
	var r;
	e.attr("id", n);
	e.find(".accordion-group").each(function(e, t) {
		r = "accordion-element-" + randomNumber();
		$(t).find(".accordion-toggle").each(function(e, t) {
			$(t).attr("data-parent", "#" + n);
			$(t).attr("href", "#" + r)
		});
		$(t).find(".accordion-body").each(function(e, t) {
			$(t).attr("id", r)
		})
	})
}
function handleCarouselIds() {
	var e = $(".drag-view #myCarousel");
	var t = randomNumber();
	var n = "carousel-" + t;
	e.attr("id", n);
	e.find(".carousel-indicators li").each(function(e, t) {
		$(t).attr("data-target", "#" + n)
	});
	e.find(".left").attr("href", "#" + n);
	e.find(".right").attr("href", "#" + n)
}
//处理模态框，模态框id，随机id
function handleModalIds() {
	var e = $(".drag-view #myModalLink");
	var t = randomNumber();
	var n = "modal-container-" + t;
	var r = "modal-" + t;
	e.attr("id", r);
	e.attr("href", "#" + n);
	e.next().attr("id", n)
}
function handleTabsIds() {
	var e = $(".drag-view #myTabs");
	var t = randomNumber();
	var n = "tabs-" + t;
	e.attr("id", n);
	e.find(".tab-pane").each(function(e, t) {
		var n = $(t).attr("id");
		var r = "panel-" + randomNumber();
		$(t).attr("id", r);
		$(t).parent().parent().find("a[href=#" + n + "]").attr("href", "#" + r)
	})
}
function randomNumber() {
	return randomFromInterval(1, 1e6)
}
function randomFromInterval(e, t) {
	return Math.floor(Math.random() * (t - e + 1) + e)
}
function gridSystemGenerator() {
	$(".lyrow .preview input").bind("keyup", function() {
		var e = 0;
		var t = "";
		var n = $(this).val().split(" ", 12);
		$.each(n, function(n, r) {
			e = e + parseInt(r);
			t += '<div class="span' + r + ' column"></div>'
		});
		if (e == 12) {
			$(this).parent().next().children().html(t);
			$(this).parent().prev().show()
		} else {
			$(this).parent().prev().hide()
		}
	})
}
function configurationElm(e, t) {
	const dragViewHtml = $(".drag-view");
	//这个事件处理器绑定到 .drag-view 类下的 .configuration 元素内部的 a 标签上。
    dragViewHtml.delegate(".configuration > a", "click", function(e) {
		//阻止默认事件
		e.preventDefault();
		const t = $(this).parent().next().next().children();
		$(this).toggleClass("active");
		t.toggleClass($(this).attr("rel"))
	});
    dragViewHtml.delegate(".configuration .dropdown-menu a", "click", function(e) {
		e.preventDefault();
		var t = $(this).parent().parent();
		var n = t.parent().parent().next().next().children();
		t.find("li").removeClass("active");
		$(this).parent().addClass("active");
		var r = "";
		t.find("a").each(function() {
			r += $(this).attr("rel") + " "
		});
		t.parent().removeClass("open");
		n.removeClass(r);
		n.addClass($(this).attr("rel"))
	})
}
function removeElm() {
	$(".drag-view").delegate(".remove", "click", function(e) {
		e.preventDefault();
		$(this).parent().remove();
		if (!$(".drag-view .lyrow").length > 0) {
			clearDragViewHtml()
		}
	})
}
function clearDragViewHtml() {
	$(".drag-view").empty();
	layouthistory = null;
	if (supportstorage())
		localStorage.removeItem("layoutdata");
}
function removeMenuClasses() {
	$("#menu-layoutit li button").removeClass("active")
}
function changeStructure(e, t) {
	$("#download-layout ." + e).removeClass(e).addClass(t)
}
function cleanHtml(e) {
	$(e).parent().append($(e).children().html())
}
function downloadLayoutSrc() {
	const e = "";
	const downloadLayout = $("#download-layout");
	downloadLayout.children().html($(".drag-view").html());
	const t = downloadLayout.children();
	t.find(".preview, .configuration, .drag, .remove").remove();
	t.find(".lyrow").addClass("removeClean");
	t.find(".box-element").addClass("removeClean");
	t.find(".lyrow .lyrow .lyrow .lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".lyrow .lyrow .lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".lyrow .lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".removeClean").remove();
	$("#download-layout .column").removeClass("ui-sortable");
	$("#download-layout .row-fluid").removeClass("clearfix").children().removeClass("column");
	if ($("#download-layout .container").length > 0) {
		changeStructure("row-fluid", "row")
	}
	formatSrc = $.htmlClean(downloadLayout.html(), {
		format: true,
		allowedAttributes: [
			["id"],
			["class"],
			["data-toggle"],
			["data-target"],
			["data-parent"],
			["role"],
			["data-dismiss"],
			["aria-labelledby"],
			["aria-hidden"],
			["data-slide-to"],
			["data-slide"]
		]
	});
	downloadLayout.html(formatSrc);
	$("#downloadModal textarea").empty();
	$("#downloadModal textarea").val(formatSrc)
}

var currentDocument = null;
var timerSave = 1000;
var stopsave = 0;
var startdrag = 0;
var dragViewHtml = $(".drag-view").html();
var currenteditor = null;
$(window).resize(function() {
	$("body").css("min-height", $(window).height() - 90);
	$(".drag-view").css("min-height", $(window).height() - 160)
});

function restoreData(){
	if (supportstorage()) {
		//历史数据
		layouthistory = JSON.parse(localStorage.getItem("layoutdata"));
		if (!layouthistory) return false;
		//数据绑定
		window.dragViewHtml = layouthistory.list[layouthistory.count-1];
		//渲染
		if (window.dragViewHtml) $(".drag-view").html(window.dragViewHtml);
	}
}

function initContainer(){
    //在div可以拖动绑定
    $(".drag-view, .drag-view .view-col").sortable({
        connectWith: ".view-row",
        opacity: .35,
        handle: ".drag",
        start: function(e,t) {
            if (!startdrag) stopsave++;
            startdrag = 1;
        },
        stop: function(e,t) {
            if(stopsave>0) stopsave--;
            startdrag = 0;
        }
    });
	configurationElm();
}
$(document).ready(function() {
	//CKEditor 会尝试自动替换页面上标记为可编辑的元素
	CKEDITOR.disableAutoInline = true;
	//初始化容器
	restoreData();
	//初始化编辑器
	const contenthandle = CKEDITOR.replace('contenteditor', {
		language: 'zh-cn',
		contentsCss: ['css/bootstrap.css'],
		allowedContent: true
	});
	//初始化容器
	$("body").css("min-height", $(window).height() - 90);
	//初始化画布
	$(".drag-view").css("min-height", $(window).height() - 160);
	//当布局组件拖动时
	$(".sidebar-nav .lyrow").draggable({
		//拖动到画布
		connectToSortable: ".drag-view",
		//拖动时，克隆
		helper: "clone",
		//拖动组件的拖动把手
		handle: ".drag",
		start: function(e,t) {
			//阻止保存
			if (!startdrag) stopsave++;
			startdrag = 1;
		},
		drag: function(e, t) {
			//拖动时，克隆
			//这个虚拟组件宽400px
			t.helper.width(400)
		},
		stop: function(e, t) {
            //当松手时，克隆
            $(".drag-view .view-row").sortable({
                //选择页面上所有 .drag-view 类下的 .column 类的元素，并初始化它们为可排序的。
                opacity: .35,//拖动时，透明度
                connectWith: ".view-row",//可以将一个 .column 内的元素拖动到另一个 .column 内。所有.column 元素都是互相连接的，允许跨容器排序
                start: function(e,t) {
                    if (!startdrag) stopsave++;
                    startdrag = 1;
                },
                stop: function(e,t) {
                    if(stopsave>0) stopsave--;
                    startdrag = 0;
                }
            });
			if(stopsave>0) stopsave--;
			startdrag = 0;
		}
	});

	//当盒子拖动时，所有组件都需要加上box的class
	$(".sidebar-nav .box").draggable({
		connectToSortable: ".column",
		helper: "clone",
		handle: ".drag",
		start: function(e,t) {
			if (!startdrag) stopsave++;
			startdrag = 1;
		},
		drag: function(e, t) {
			t.helper.width(400)
		},
		stop: function() {
			handleJsIds();
			if(stopsave>0) stopsave--;
			startdrag = 0;
		}
	});
	initContainer();
	$('body.edit .drag-view').on("click","[data-target=#editorModal]",function(e) {
		e.preventDefault();
		currenteditor = $(this).parent().parent().find('.view');
		var eText = currenteditor.html();
		contenthandle.setData(eText);
	});
	$("#savecontent").click(function(e) {
		e.preventDefault();
		currenteditor.html(contenthandle.getData());
	});
	$("[data-target=#downloadModal]").click(function(e) {
		e.preventDefault();
		downloadLayoutSrc();
	});
	$("[data-target=#sourceModal]").click(function(e) {
		e.preventDefault();
		$('#sourceeditor').val($(".drag-view").html());
	});
	$("#savesource").click(function(){
		$('.drag-view').html($('#sourceeditor').val());
		initContainer();
		return;
	});
	$("[data-target=#shareModal]").click(function(e) {
		e.preventDefault();
		handleSaveLayout();
	});
	$("#download").click(function() {
		downloadLayout();
		return false;
	});
	$("#downloadhtml").click(function() {
		downloadHtmlLayout();
		return false
	});
	$("#edit").click(function() {
		$("body").removeClass("devpreview sourcepreview");
		$("body").addClass("edit");
		removeMenuClasses();
		$(this).addClass("active");
		return false
	});
	$("#clear").click(function(e) {
		e.preventDefault();
		cleardrag-view()
	});
	$("#devpreview").click(function() {
		$("body").removeClass("edit sourcepreview");
		$("body").addClass("devpreview");
		removeMenuClasses();
		$(this).addClass("active");
		return false
	});
	$("#sourcepreview").click(function() {
		$("body").removeClass("edit");
		$("body").addClass("devpreview sourcepreview");
		removeMenuClasses();
		$(this).addClass("active");
		return false
	});
	$("#fluidPage").click(function(e) {
		e.preventDefault();
		changeStructure("container", "container-fluid");
		$("#fixedPage").removeClass("active");
		$(this).addClass("active");
		downloadLayoutSrc()
	});
	$("#fixedPage").click(function(e) {
		e.preventDefault();
		changeStructure("container-fluid", "container");
		$("#fluidPage").removeClass("active");
		$(this).addClass("active");
		downloadLayoutSrc()
	});
	$(".nav-header").click(function() {
		$(".sidebar-nav .boxes, .sidebar-nav .rows").hide();
		$(this).next().slideDown()
	});
	$('#undo').click(function(){
		stopsave++;
		if (undoLayout()) initContainer();
		stopsave--;
	});
	$('#redo').click(function(){
		stopsave++;
		if (redoLayout()) initContainer();
		stopsave--;
	});
	removeElm();
	gridSystemGenerator();
	setInterval(function() {
		handleSaveLayout()
	}, timerSave)
})
let MobileMode = 0;
//切换手机模式
function changeMobileMode() {
	if (MobileMode === 0){
		//初始化画布
		$(".drag-view").css("min-height", 920);
		$(".drag-view").css("max-width", 430);
		MobileMode = 1;
	}else{
		//初始化画布
		$(".drag-view").css("min-height", $(window).height() - 160);
		$(".drag-view").css("max-width", $(window).width());
		MobileMode = 0;
	}

	//再次点击时先判断当前是否为手机模式

}
